import React from 'react'
import { connect } from 'react-redux'
import { messages, getDefaultPermissionSetOfBook, getDefaultPermissionCompany } from "share/common";
import { Form, Input, Switch, Button, message, Spin, Radio, Popover, Icon, Select, Tooltip, Checkbox } from 'antd'
import approveSuggestService from 'containers/setting/approve-suggest/approve-suggest.service'
const CheckboxGroup = Checkbox.Group;
const { TextArea } = Input;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Option = Select.Option;
import errorMessage from "share/errorMessage";
import "styles/setting/workflow-config/new-workflow-config.scss"
import Priority from 'components/template/priority'
import FloatDays from 'containers/application-setting/comp/floatDays'
import workflowMatrixService from 'containers/setting/workflow-matrix/workflow-matrix.service';
const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14, offset: 1 },
};

const selectOptions = [{
  value: 3001,
  label: messages('request-4.key562')/*顺序*/
}, {
  value: 3002,
  label: messages('request-4.key563')/*并列*/
}];

class NewMatrix extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isShowLoading: false,
      configFp: [],
      configFunctionProfile: {},
      levelConfig: {},
      saveLoading: false,
      topPermission: '', levelCode: '', levelOrgId: '', defaultValue: {},
      matrixParams: {
        "approvalMatrixId": null,
        "levelCode": "",
        "levelOrgId": "",
        "visibleCompanyScope": 1,
        "visibleCompanyRelation": null,
        "name": "",
      },
      loading: false,
    }
  }

  componentDidMount() {
    let { topPermission, defaultValue, id } = this.props.params;
    let { matrixParams }=this.state;
    if (id) {
      this.setState({ loading: true })
      workflowMatrixService.getWorkflowMatrix(id)
        .then(res => {
          if (res && res.data) {
            matrixParams = res.data;
            defaultValue.distribution = {
              companies: res.data.visibleCompanyRelation
            }
          }
          this.setState({ loading: false, matrixParams, defaultValue, topPermission })
        })
        .catch(err => {
          this.setState({ loading: false })
          errorMessage(err.response);
        })
    } else {
      matrixParams.levelCode = topPermission;
      matrixParams.levelOrgId = defaultValue.levelOrgId;
      this.setState({
        matrixParams,
        topPermission: topPermission,
        defaultValue: defaultValue
      })
    }

  }

  //清空配置type为select类型的可选范围以及已选值
  clearSelectData = (isClearDataList) => {
    const { levelConfig, configFp } = this.state;
    const { setFieldsValue } = this.props.form;
    let setData = {};
    configFp.forEach(config => {
      config.groupList.forEach(groupItem => {
        if (groupItem.type === 'select' && groupItem.dependCode) {
          if (isClearDataList) {
            groupItem.dataList = [];
          }
          setData[groupItem.fpCode] = undefined;
        }
      });
    });
    isClearDataList && this.setState({ configFp });
    setFieldsValue(setData);
  };

  //保存
  handleSave = e => {
    e.preventDefault();
    const { form } = this.props;
    const { matrixParams } = this.state;
    if (matrixParams && !matrixParams.levelOrgId) {
      message.error(messages('request-4.key590')/*请选择所属组织*/);
      return;
    }
    if (matrixParams && matrixParams.visibleCompanyScope === 2 && ( !matrixParams.visibleCompanyRelation || matrixParams.visibleCompanyRelation.length === 0)) {
      message.error(messages('request-4.key591')/*请选择公司*/);
      return;
    }
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { head } = this.state;
        let params = Object.assign({}, head, matrixParams, values,);
        this.setState({
          saveLoading: true,
        });
        workflowMatrixService.postWorkflowMatrix(params).then(res => {
          this.setState({ saveLoading: false });
          this.props.close(true);
        }).catch(e => {
          this.setState({ saveLoading: false });
          errorMessage(e.response)
        })

      }
    })
  };

  handleChangePriority = res => {
    const { matrixParams } = this.state;
    if (res) {
      matrixParams.levelOrgId = res.levelOrgId;
      matrixParams.levelCode = res.levelCode;
      if (res.distribution) {
        matrixParams.visibleCompanyScope = 2;
        matrixParams.visibleCompanyRelation = res.distribution.companies;
      }
    } else {
      matrixParams.levelOrgId = null;
    }
    this.setState({ matrixParams })
  };


  render() {
    const { matrixParams, loading, topPermission, saveLoading } = this.state;
    let { defaultValue }=this.state;
    const { getFieldDecorator } = this.props.form;
    return (
      <div className="new-workflow-config">
        { !loading && <Form className="new-form" onSubmit={this.handleSave}>
          <Spin spinning={loading}>
            {defaultValue.levelOrgId && <Priority
              style={{ marginLeft: 0 }}
              onChange={this.handleChangePriority}
              formItemLayout={this.props.params.formItemLayout || formItemLayout}
              top={defaultValue.range}
              showCompany
              disabledTop={!!this.props.params.id}
              defaultValue={defaultValue}
              disabled={!!this.props.params.id && matrixParams.levelCode === 'COMPANY'}
              companyProps={{
                single: true,
              }}
            />}
            <FormItem
              {...formItemLayout}
              label={messages('request-4.key592')/*名称*/}>
              {getFieldDecorator('name', {
                initialValue: matrixParams.name,
                rules: [{
                  required: true,
                  message: messages('common.please.input')/*请输入*/,
                }]
              })(
                <Input/>
              )}
            </FormItem>
          </Spin>
          <div className="footer-operate" style={{ backgroundColor: '#ffffff', left: '0px' }}>
            <Button
              type="primary"
              htmlType="submit"
              style={{ margin: '0px 10px' }}
              loading={saveLoading}
            >
              {messages('common.ok')/*确定*/}
            </Button>
            <Button onClick={this.props.close}>{messages('common.cancel')/*取消*/}</Button>
          </div>
        </Form>}
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
    tenantMode: state.main.tenantMode,
    authPolicyAll: state.main.authPolicyAll,
    currentMenuPermission: state.main.currentMenuPermission,
  }
}
const wrappedNewMatrix = Form.create()(NewMatrix);
export default connect(mapStateToProps)(wrappedNewMatrix);
